package com.listeningframework.boot.autoconfigure.webmvc.validate;

import org.apache.commons.collections.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;

/**
 * 
 * Validations Utils
 *
 * @author Listening
 * @version $Id: Validations.java, v 0.1 2016年5月5日 下午9:13:30 Listening Exp $
 */
public class Validations {
    /**
     * Instance
     */
    private static final Validator validator = getInstance();

    /**
     * Construct
     */
    private Validations() {
    }

    /**
     * Get Validator Instance
     *
     * @return Validator
     */
    private static final Validator getInstance() {
        return Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 验证对象合法性
     *
     * @param obj 待验证对象
     * @param <T> 验证对象泛型
     * @return T
     */
    public static <T> ValidationResult validate(T obj) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (CollectionUtils.isEmpty(set)) {
            return result;
        }
        result.setHasErrors(true);
        for (ConstraintViolation<T> cv : set) {
            result.addErrorMsg(cv.getPropertyPath().toString(), cv.getMessage());
        }
        return result;
    }

    /**
     * Validate Object Property
     *
     * @param obj 待验证对象
     * @param propertyName 属性
     * @param <T> 泛型类型
     * @return ValidationResult
     */
    public static <T> ValidationResult validate(T obj, String propertyName) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
        if (CollectionUtils.isEmpty(set)) {
            return result;
        }
        result.setHasErrors(true);
        for (ConstraintViolation<T> cv : set) {
            result.addErrorMsg(cv.getPropertyPath().toString(), cv.getMessage());
        }
        return result;
    }
}
